#include "PathFind.h"
#include <sys/stat.h>

using namespace inf;

bool PathFinder::DirIsDots( const char *str ) {
	return ( str[0] == '.' && ( str[1] == '\0' || (str[1] == '.' && str[2] == '\0' ) ) );
}

bool PathFinder::IsDir(const char* osPath) {
	struct _stat stat_Info;
	if ( _stat ( osPath, &stat_Info ) == -1 )
		return false;
	return (stat_Info.st_mode & S_IFDIR) != 0;
}

PathFinder* PathFinder::Create(const char *dir) {
    PathFinder* finder = new PathFinder(dir);

    // get first
    inf::Str findName = finder->GetStartDir();
    finder->nameOffset = findName.length();
    findName += "*.*";
    //findName += finder->ext;
    finder->hFind = _findfirst( findName, &finder->findData );
    if( finder->hFind == -1 )
    {
        delete finder;
        return NULL;
    }

    // init finder
    finder->nameBuffer = findName;
    finder->nameBuffer.cap_length(finder->nameOffset);
    if (finder->nameBuffer[finder->nameOffset - 1] != '/')
        finder->nameBuffer += '/';
    finder->nameBuffer += finder->findData.name;
    finder->name = finder->nameBuffer.c_str() + finder->startDir.length();
    finder->isDir = (finder->findData.attrib & _A_SUBDIR) != 0;
    if( finder->isDir )
        finder->isDots = DirIsDots( finder->findData.name );
    else
        finder->isDots = false;
    return finder;
}

void PathFinder::Close( PathFinder* finder ) {
    if(!finder) return;

    _findclose(finder->hFind);
    delete finder;
}

PathFinder::PathFinder(const char* dir) {
	startDir = dir;
    startDir.backslashes_to_slashes();
	if(startDir.back() != '/')
		startDir += "/";

}

PathFinder::~PathFinder() {

}

const Str& PathFinder::GetStartDir() const
{
    return startDir;
}

Str& PathFinder::GetStartDir()
{
    return startDir;
}

bool PathFinder::GetNext() {
    if ( _findnext( hFind, &findData ) != -1 ) {
        nameBuffer.cap_length( nameOffset );

        if (nameBuffer.last('/') != nameOffset - 1)
            nameBuffer += '/';
        nameBuffer += findData.name;
        name = nameBuffer.c_str() + startDir.length();
        isDir = (findData.attrib & _A_SUBDIR) != 0;
        if ( isDir )
            isDots = DirIsDots( findData.name );
        else
            isDots = false;
        return true;
    }
	return false;
}

